package com.wind.plugin.openAction.utils;

import cn.hutool.core.util.XmlUtil;
import org.w3c.dom.Document;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;

public class Util {

    public static String formatXml(String xmlString) {
        try {
            // 使用 Hutool 的 XmlUtil 解析 XML 字符串为 Document 对象
            Document document = XmlUtil.parseXml(xmlString);

            // 创建 TransformerFactory 和 Transformer 对象，并设置输出属性
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            // 将 Document 转换为 Source
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(new StringWriter());

            // 使用 Transformer 对象进行格式化
            transformer.transform(source, result);

            // 获取格式化后的 XML 字符串
            String prettyXml = result.getWriter().toString();

            // 删除空行
            prettyXml = prettyXml.replaceAll("(?m)^\\s*$\\r?\\n", "");

            return prettyXml;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
